package com.base.cn.platform.os.controller.manage.teacher;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.manage.teacher.SysTeacher;
import com.base.cn.platform.os.entity.manage.teacher.SysTeacherCondition;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 讲师Controller
 *
 * @author s.li
 * @create 2018-04-08-14:46
 */
@RestController
@RequestMapping("/manage")
public class SysTeacherController extends BaseController {

    @Autowired
    private SysTeacherBiz sysTeacherBiz;

    /**
     * 查询讲师数据量
     * @return BigDecimal
     */
    @RequestMapping("/countTeacher")
    public BigDecimal countTeacher(@RequestBody SysTeacherCondition condition){
        return  sysTeacherBiz.getCount(condition);
    }

    /**
     * 保存讲师接口
     * @param sysTeacher 讲师数据对象
     * @return Map<String,Object>
     */
    @RequestMapping("/saveSysTeacher")
    public Map<String,Object> saveSysTeacher(@RequestBody SysTeacher sysTeacher){
        if(StringUtils.isEmpty(sysTeacher.getTeacherName())){
            return ResultUtil.ERROR("讲师名称不能为空");
        }
        String message = StringUtils.checkSubjectCondition(sysTeacher.getSubjectIds());
        if(message !=null){
            return ResultUtil.ERROR(message);
        }
        if(StringUtils.isEmpty(sysTeacher.getImageJson())){
            return ResultUtil.ERROR("请上传讲师头像");
        }
        if(StringUtils.isEmpty(sysTeacher.getDepict())){
            return ResultUtil.ERROR("请填写讲师描述信息");
        }
        if(ObjectUtils.isEmpty(sysTeacher.getTeacherType())){
            return ResultUtil.ERROR("请选择讲师性质类型");
        }
        if(StringUtils.isEmpty(sysTeacher.getTeacherIdentity())){
            return ResultUtil.ERROR("请选择讲师身份");
        }
        if(sysTeacher.getIsQuestion().intValue()==1){//如果是提问讲师
            if(ObjectUtils.isEmpty(sysTeacher.getQuestionFee())){
                return ResultUtil.ERROR("请填写提问费用金额");
            }if(sysTeacher.getQuestionFee()>10000){
                return ResultUtil.ERROR("提问费用不得超过10000");
            }

            if(ObjectUtils.isEmpty(sysTeacher.getSeparateInto())){
                return ResultUtil.ERROR("请填写分成比例");
            }
            if(sysTeacher.getSeparateInto().doubleValue()>100D || sysTeacher.getSeparateInto().doubleValue()<0){
                return ResultUtil.ERROR("分成比例请填写0-100间，且必须是整数");
            }
            if(ObjectUtils.isEmpty(sysTeacher.getQaTypeId()) || sysTeacher.getQaTypeId().compareTo(new BigDecimal(0))<=0){
                return ResultUtil.ERROR("请选择问答分类");
            }
        }
        //执行保存讲师数据
        sysTeacher.setStatus(1);
        sysTeacher = sysTeacherBiz.saveSysTeacher(sysTeacher);
        return ResultUtil.SUCCESS("讲师保存成功",sysTeacher);
    }

    /**
     * 通过讲师ID，查询讲师数据
     * @param id 讲师ID
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @param courseData 是否查询关联课程数据，true是，false否
     * @param qaTypeData 是否查询关联问答分类，true是，false否
     * @return SysTeacher 讲师对象
     */
    @RequestMapping("/findSysTeacherById")
    public SysTeacher findSysTeacherById(@RequestParam("id") BigDecimal id,
                                         @RequestParam("subjectData") boolean subjectData,
                                         @RequestParam("createUser") boolean createUser,
                                         @RequestParam("sysUserData") boolean sysUserData,
                                         @RequestParam("courseData") boolean courseData,
                                         @RequestParam("qaTypeData") boolean qaTypeData){
        return sysTeacherBiz.findSysTeacherById(id,subjectData,createUser,sysUserData, courseData, qaTypeData);
    }

    /**
     * 通过讲师ID串，查询讲师数据
     * @param ids 讲师ID串
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @return List<SysTeacher> 讲师数据列表
     */
    @RequestMapping("/findSysTeacherByIds")
    public List<SysTeacher> findSysTeacherByIds(@RequestParam("ids") String ids,
                                                @RequestParam("subjectData") boolean subjectData,
                                                @RequestParam("createUser") boolean createUser,
                                                @RequestParam("sysUserData") boolean sysUserData,
                                                @RequestParam("courseData") boolean courseData,
                                                @RequestParam("qaTypeData") boolean qaTypeData){
        return sysTeacherBiz.findSysTeacherByIds(ids,subjectData,createUser,sysUserData, courseData, qaTypeData);
    }

    /**
     * 通过讲师ID串，查询讲师数据
     * @param ids 讲师ID串
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @param courseData 是否查询关联课程数据，true是，false否
     * @param qaTypeData 是否查询关联问答数据，true是，false否
     * @return Map<BigDecimal,SysTeacher> 讲师数据集合
     */
    @RequestMapping("/findSysTeacherToMapByIds")
    public Map<BigDecimal,SysTeacher> findSysTeacherToMapByIds(@RequestParam("ids") String ids,
                                                               @RequestParam("subjectData") boolean subjectData,
                                                               @RequestParam("createUser") boolean createUser,
                                                               @RequestParam("sysUserData") boolean sysUserData,
                                                               @RequestParam("courseData") boolean courseData,
                                                               @RequestParam("qaTypeData") boolean qaTypeData){
        return sysTeacherBiz.findSysTeacherToMapByIds(ids,subjectData,createUser,sysUserData, courseData, qaTypeData);
    }

    /**
     * 多条件，查询讲师数据
     * @param condition 查询条件对象
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @return List<SysTeacher> 讲师数据列表
     */
    @RequestMapping("/findSysTeacherList")
    public List<SysTeacher> findSysTeacherList(@RequestBody SysTeacherCondition condition,
                                               @RequestParam("subjectData") boolean subjectData,
                                               @RequestParam("createUser") boolean createUser,
                                               @RequestParam("sysUserData") boolean sysUserData,
                                               @RequestParam("courseData") boolean courseData,
                                               @RequestParam("qaTypeData") boolean qaTypeData){
        return sysTeacherBiz.findSysTeacherList(condition,subjectData,createUser,sysUserData, courseData, qaTypeData);
    }

    /**
     * 分页，查询讲师数据（用于前台）
     * @param condition 查询条件对象
     * @param currentPage 当前页码
     * @param pageSize 页面显示数据量
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @return PageInfo<SysTeacher> 讲师数据列表
     */
    @RequestMapping("/findWebTeacherListPage")
    public PageInfo<SysTeacher> findWebTeacherListPage(@RequestBody SysTeacherCondition condition,
                                                       @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                       @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize,
                                                       @RequestParam("subjectData") boolean subjectData,
                                                       @RequestParam("createUser") boolean createUser,
                                                       @RequestParam("sysUserData") boolean sysUserData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return sysTeacherBiz.findSysTeacherList(condition,page,subjectData,createUser,sysUserData);
    }
    /**
     * 分页，查询讲师数据
     * @param condition 查询条件对象
     * @param currentPage 当前页码
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @return PageInfo<SysTeacher> 讲师数据列表
     */
    @RequestMapping("/findSysTeacherListPage")
    public PageInfo<SysTeacher> findSysTeacherListPage(@RequestBody SysTeacherCondition condition,
                                                       @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                       @RequestParam("subjectData") boolean subjectData,
                                                   @RequestParam("createUser") boolean createUser,
                                                   @RequestParam("sysUserData") boolean sysUserData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        return sysTeacherBiz.findSysTeacherList(condition,page,subjectData,createUser,sysUserData);
    }

    /**
     * 修改讲师状态
     * @param ids 讲师ID串
     * @param status 状态，1正常，2禁用，3删除
     */
    @RequestMapping("/updateSysTeacherStatus")
    public Map<String,Object> updateSysTeacherStatus(@RequestParam("ids") String ids,
                                                     @RequestParam("status") int status){
        sysTeacherBiz.updateSysTeacherStatus(ids,status);
        return ResultUtil.SUCCESS("讲师状态修改成功");
    }

    /**
     * 根据sql语句查询讲师集合
     * @param whereSql 查询语句
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @return teacherMap集合
     */
    @RequestMapping("/findTeacherMapList")
    public List<SysTeacher> findTeacherMapList(@RequestParam("whereSql")String whereSql,
                                                        @RequestParam("subjectData") boolean subjectData,
                                                        @RequestParam("createUser") boolean createUser,
                                                        @RequestParam("sysUserData") boolean sysUserData){
        return sysTeacherBiz.findTeacherMapList(whereSql, subjectData, createUser, sysUserData);
    }

    /**
     * 根据sql查询讲师ID及讲师名称的集合
     * @param whereSql 查询语句
     * @param subjectData 是否查询专业数据，true是，false否
     * @param createUser 是否查询创建人数据，true是，false否
     * @param sysUserData 是否查询关联用户数据，true是，false否
     * @return teacherMap集合
     */
    @RequestMapping("/findTeacherToMapList")
    public Map<BigDecimal,String> findTeacherToMapList(@RequestParam("whereSql")String whereSql,
                                               @RequestParam("subjectData") boolean subjectData,
                                               @RequestParam("createUser") boolean createUser,
                                               @RequestParam("sysUserData") boolean sysUserData){
        return sysTeacherBiz.findTeacherToMapList(whereSql, subjectData, createUser, sysUserData);
    }

    /**
     * 修改老师的问题数和学生数(加)
     * @param teacherId 老师ID
     * @param questionNum 是否修改问题数
     * @param userNum 是否修改学生数
     * @return Map<String, Object>
     */
    @RequestMapping("/updateQuestionNumAndUserNum")
    public Map<String, Object> updateQuestionNumAndUserNum(@RequestParam("teacherId") BigDecimal teacherId,
                                                           @RequestParam("questionNum") boolean questionNum,
                                                           @RequestParam("userNum") boolean userNum){
        return updateQuestionNumAndUserNum(teacherId,questionNum,userNum,1);
    }

    /**
     * 修改老师的问题数和学生数(减)
     * @param teacherId 老师ID
     * @param questionNum 是否修改问题数
     * @param userNum 是否修改学生数
     * @return Map<String, Object>
     */
    @RequestMapping("/updateQuestionNumAndUserNumReduce")
    public Map<String, Object> updateQuestionNumAndUserNumReduce(@RequestParam("teacherId") BigDecimal teacherId,
                                                           @RequestParam("questionNum") boolean questionNum,
                                                           @RequestParam("userNum") boolean userNum){
        return updateQuestionNumAndUserNum(teacherId,questionNum,userNum,-1);
    }

    /**
     * 修改老师的问题数和学生数(批量)
     * @param listMap 老师ID及对应问答列表
     * @param questionNum 是否修改问题数
     * @param userNum 是否修改学生数
     * @param isAdd 是否批量加（否为批量减）
     * @return Map<String, Object>
     */
    @RequestMapping("/updateQuestionNumAndUserNumBatch")
    public Map<String, Object> updateQuestionNumAndUserNumBatch(@RequestBody Map<BigDecimal,Integer> listMap,
                                                                 @RequestParam("questionNum") boolean questionNum,
                                                                 @RequestParam("userNum") boolean userNum,
                                                                @RequestParam("isAdd") boolean isAdd){
        if (ObjectUtils.isNotEmpty(listMap)){
            StringBuffer stringBuffer = new StringBuffer();
            listMap.forEach((k,v) -> stringBuffer.append(k).append(","));
            String teacherIds = StringUtils.subHeadTailString(stringBuffer.toString(),",");
            List<SysTeacher> teacherList = sysTeacherBiz.findSysTeacherByIds(teacherIds,false,false,false,false,false);
            if(ObjectUtils.isNotEmpty(teacherList)){
                Map<BigDecimal,SysTeacher> teacherMap = teacherList.stream().collect(Collectors.toMap(e -> e.getId(),e -> e));
                List<SysTeacher> newTeacherList = new LinkedList<>();
                listMap.forEach((k,v) -> {
                    SysTeacher sysTeacher = new SysTeacher();
                    sysTeacher.setId(k);
                    if(questionNum){
                        if(isAdd){
                            sysTeacher.setQuestionNum(teacherMap.get(k).getQuestionNum()+v);
                        }else {
                            sysTeacher.setQuestionNum(teacherMap.get(k).getQuestionNum()-v);
                        }
                    }
                    if(userNum){
                        if(isAdd) {
                            sysTeacher.setUserNum(teacherMap.get(k).getUserNum() + v);
                        }else{
                            sysTeacher.setUserNum(teacherMap.get(k).getUserNum() - v);
                        }
                    }
                    newTeacherList.add(sysTeacher);
                });
                sysTeacherBiz.updateBatch(newTeacherList);
                return ResultUtil.SUCCESS("修改成功");
            }
        }
        return ResultUtil.ERROR();
    }

    /**
     * 修改老师的问题数和学生数
     * @param teacherId 老师ID
     * @param questionNum 是否修改问题数
     * @param userNum 是否修改学生数
     * @param num 加1 或 减1
     * @return
     */
    private Map<String, Object> updateQuestionNumAndUserNum(BigDecimal teacherId,boolean questionNum,boolean userNum,int num){
        SysTeacher sysTeacher = sysTeacherBiz.findById(teacherId);
        if(ObjectUtils.isNotEmpty(sysTeacher)){
            if(questionNum){
                sysTeacher.setQuestionNum(sysTeacher.getQuestionNum() + num);
            }
            if(userNum){
                sysTeacher.setUserNum(sysTeacher.getUserNum() + num);
            }
            sysTeacherBiz.saveSysTeacher(sysTeacher);
            return ResultUtil.SUCCESS("修改成功");
        }
        return ResultUtil.ERROR();
    }

    /**
     * 更新讲师课程量
     * @param teacherCourseNumData 前置数据
     */
    @RequestMapping("/updateTeacherCourseNum")
    public void updateTeacherCourseNum(@RequestBody Map<String,List<Map<BigDecimal,String>>> teacherCourseNumData){
        List<Map<BigDecimal,String>> addList = teacherCourseNumData.get("add");
        List<Map<BigDecimal,String>> subList = teacherCourseNumData.get("sub");
        Map<BigDecimal,Integer> addNumMap = new HashMap<>();
        Map<BigDecimal,Integer> subNumMap = new HashMap<>();
        if(ObjectUtils.isNotEmpty(addList)){
            addList.forEach(map->{
                map.forEach((k,v)->{
                    String[] arr = StringUtils.subHeadTailString(v,",").split(",");
                    Arrays.stream(arr).forEach(teacherId->{
                        BigDecimal _teacherId = new BigDecimal(teacherId);
                        Integer num = addNumMap.get(_teacherId);
                        if(num==null){
                            addNumMap.put(_teacherId,1);
                        }else{
                            addNumMap.put(_teacherId,num.intValue()+1);
                        }
                    });
                });
            });
        }
        if(ObjectUtils.isNotEmpty(subList)){
            subList.forEach(map->{
                map.forEach((k,v)->{
                    String[] arr = StringUtils.subHeadTailString(v,",").split(",");
                    Arrays.stream(arr).forEach(teacherId->{
                        if(StringUtils.isNotEmpty(teacherId)){
                            BigDecimal _teacherId = new BigDecimal(teacherId);
                            Integer num = subNumMap.get(_teacherId);
                            if(num==null || num.intValue() < 0){
                                subNumMap.put(_teacherId,1);
                            }else{
                                subNumMap.put(_teacherId,num.intValue()+1);
                            }
                        }
                    });
                });
            });
        }
        //合并两个Map
        if(ObjectUtils.isNotEmpty(addNumMap) && ObjectUtils.isNotEmpty(subNumMap)){
            addNumMap.forEach((addK,addV)->{
                Integer subV = subNumMap.get(addK);
                if(subV !=null ){
                    int nV = addV.intValue() - subV.intValue();
                    if(nV < 0){
                        nV = 0;
                    }
                    addNumMap.put(addK,nV);
                    subNumMap.remove(addK);
                }
            });
        }
        String teacherIds = "";
        if(ObjectUtils.isNotEmpty(addNumMap)){
            teacherIds += addNumMap.keySet().stream().map(e->e.toString()).collect(Collectors.joining(","));
        }
        if(ObjectUtils.isNotEmpty(subNumMap)){
            if(StringUtils.isNotEmpty(teacherIds)){
                teacherIds = ",";
            }
            teacherIds += subNumMap.keySet().stream().map(e->e.toString()).collect(Collectors.joining(","));
        }
        if(StringUtils.isEmpty(teacherIds)){
            return;
        }
        //得到讲师列表
        List<SysTeacher> teacherList = sysTeacherBiz.findSysTeacherByIds(teacherIds,false,false,false, false, false);
        if(ObjectUtils.isNotEmpty(teacherList)){
            teacherList.forEach(teacher ->{
                if(ObjectUtils.isNotEmpty(addNumMap)){
                    Integer num = addNumMap.get(teacher.getId());
                    if(num !=null){
                        teacher.setCourseNum(teacher.getCourseNum().intValue()+num);
                    }
                }
                if(ObjectUtils.isNotEmpty(subNumMap)){
                    Integer num = subNumMap.get(teacher.getId());
                    if(num !=null){
                        int _num = teacher.getCourseNum().intValue()-num;
                        if(_num < 0){
                            _num = 0;
                        }
                        teacher.setCourseNum(_num);
                    }
                }
            });
            sysTeacherBiz.updateBatch(teacherList);
        }
    }


    /**
     * 通过讲师ID串，查询讲师数据 id in ("+ids+")
     * @return Map<BigDecimal,SysTeacher> 讲师数据集合
     */
    @RequestMapping("/findSysTeacherToMapBySimpleIds")
    public Map<BigDecimal,SysTeacher> findSysTeacherToMapBySimpleIds(@RequestParam("ids") String ids){
        return sysTeacherBiz.findSysTeacherToMapBySimpleIds(ids);
    }

    /**
     * 通过讲师ID，获取可以提交的讲师数据
     * @param teacherId 老师ID
     * @return SysTeacher
     */
    @RequestMapping("/findQaTeacherById")
    public SysTeacher findQaTeacherById(@RequestParam("teacherId") BigDecimal teacherId){
        SysTeacherCondition condition = new SysTeacherCondition();
        condition.setId(teacherId);
        condition.setIsQuestion(1);
        condition.setStatus(1);
        List<SysTeacher> teacherList = sysTeacherBiz.findSysTeacherList(condition,false,false,false,false,false);
        if(ObjectUtils.isNotEmpty(teacherList)){
            return teacherList.get(0);
        }
        return null;
    }

    /**
     * 修改老师账户
     * @param teacher
     * @return Map<String,Object>
     */
    @RequestMapping("/updateTeacherAccount")
    public Map<String,Object> updateTeacherAccount(@RequestBody SysTeacher teacher){
        if(!DataUtil.idIsNotNull(teacher.getId())){
            return ResultUtil.ERROR("老师数据不存在");
        }
        if(StringUtils.isEmpty(teacher.getRealName())){
            return ResultUtil.ERROR("请填写账号名真实姓名");
        }
        if(StringUtils.isEmpty(teacher.getAccount()) || teacher.getAccount().trim().equals("")){
            if(teacher.getAccountType().intValue()==1){
               return ResultUtil.ERROR("未绑定微信信息");
            }
            if(teacher.getAccountType().intValue()==2){
                return ResultUtil.ERROR("请填写支付宝账号");
            }
        }
        sysTeacherBiz.updateById(teacher,null);
        return ResultUtil.SUCCESS();
    }


    /**
     * 分页，查询讲师数据
     * @param condition 查询条件对象
     * @param currentPage 当前页码
     * @return PageInfo<SysTeacher> 讲师数据列表
     */
    @RequestMapping("/findSysTeacherCommissionListPage")
    public PageInfo<SysTeacher> findSysTeacherCommissionListPage(@RequestBody SysTeacherCondition condition,
                                                       @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(12);
        return sysTeacherBiz.findSysTeacherCommissionListPage(condition,page);
    }
}
